package com.ibpd.henuocms.common;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Scanner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.assist.ExtUserPermissionEntity;
import com.ibpd.henuocms.assist.PermissionModelEntity;
import com.ibpd.henuocms.entity.FunEntity;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.RoleEntity;
import com.ibpd.henuocms.entity.RolePermissionEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.entity.UserEntity;
import com.ibpd.henuocms.service.TestService;
import com.ibpd.henuocms.service.fun.FunServiceImpl;
import com.ibpd.henuocms.service.fun.IFunService;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.role.IRolePermissionService;
import com.ibpd.henuocms.service.role.IRoleService;
import com.ibpd.henuocms.service.role.RolePermissionServiceImpl;
import com.ibpd.henuocms.service.role.RoleServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.henuocms.service.user.IUserRoleService;
import com.ibpd.henuocms.service.user.UserRoleServiceImpl;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.entity.TenantEntity;

public class SysUtil {
	   public short getPid(){
	       return Short.parseShort(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
	   }
	 
	   public byte[] getMac() throws SocketException {
	       byte[] mac=null;
	       Enumeration<NetworkInterface> es= NetworkInterface.getNetworkInterfaces();
	       while(es.hasMoreElements()){
	           NetworkInterface n=es.nextElement();
	           if(null!=n.getHardwareAddress()){
	               mac=n.getHardwareAddress();
	           }
	           if(n.getDisplayName().contains("eth")){
	               break;
	           }
	       }
	       return mac;
	   }
	    public static boolean isRunning(String proName) {
	        try {
	            Process process = Runtime.getRuntime().exec("tasklist");
	            Scanner in = new Scanner(process.getInputStream());
	            while (in.hasNextLine()) {
	                String p = in.nextLine();
	                if (p.contains(proName)) {
	                    return true;
	                }
	            }
	            in.close();
	        } catch (IOException e) {
//	            log.error(String.format("Check process[%s] running error: " + e.getMessage(), proName));
	        }
	         
	        return false;
	    }
	     
	    public static int findProcessId(String proName) {
	        try {
	            Process process = Runtime.getRuntime().exec("tasklist");
	            Scanner in = new Scanner(process.getInputStream());
	            while (in.hasNextLine()) {
	                String p = in.nextLine();
	                if (p.contains(proName)) {
	                    p = p.replaceAll("\\s+", ",");
	                    IbpdLogger.getLogger(SysUtil.class).info(p);
	                    String[] arr = p.split(",");
	                    int s=(arr[1]!=null)?Integer.parseInt(arr[1]):-1;
	                    return s;
	                }
	            }
	            in.close();
	        } catch (IOException e) {
//	            log.error(String.format("Find process[%s] id error: " + e.getMessage(), proName));
	        }
	         
	        return -1;
	    }
	    public static boolean killProcess(int pid) {
	        try {
	            Runtime.getRuntime().exec("cmd.exe /c taskkill /f /pid " + pid);
	        } catch (IOException e) {
//	            log.error(String.format("Kill process[id=%d] error: " + e.getMessage(), pid));
	            return false;
	        }
	         
	        return true;
	    }
	     
	    public static boolean killProcess(String proName) {
	        int pid = findProcessId(proName);
	        if (pid == -1) return true;
	        return killProcess(pid);
	    }
	     
	     
	    public static boolean killProcessBlock(String proName) {
	        int pid = findProcessId(proName);
	        if (pid == -1) return true;
	        do {
	            killProcess(pid);
	            try {
	                Thread.sleep(100);
	            } catch (InterruptedException e) {
	            }
	        } while (isRunning(proName));
	         
	        return true;
	    }
	     
	    public static void listProcess() {
	        try {
	            Process process = Runtime.getRuntime().exec("tasklist");
	         
	            Scanner in = new Scanner(process.getInputStream());
	            while (in.hasNextLine()) {
	            	IbpdLogger.getLogger(SysUtil.class).info(in.nextLine());
	            }
	            in.close();
	        } catch (IOException e) {
	        }
	    }
	     
	    public static void main(String[] args) {
	        long t1 = System.currentTimeMillis();
	        listProcess();
	        long t2 = System.currentTimeMillis();
	        IbpdLogger.getLogger(SysUtil.class).info("Used time: " + (t2 - t1));
	         
	         
	        String proName = "Foxmail.exe";
//	      int pid = findProcessId(proName);
//	      System.out.println(pid);
//	      killProcess(pid);
	          
	         boolean b = killProcessBlock(proName);
	         long t3 = System.currentTimeMillis();
	         IbpdLogger.getLogger(SysUtil.class).info("Used time: " + (t3 - t2));
	         IbpdLogger.getLogger(SysUtil.class).info(b);
	    }
	    public static final String CURRENT_LOGIN_USER_ENTTIY="currentLoginedUserEntity";
	    public static final String CURRENT_LOGIN_USER_TENANT="loginedUserTenant";
	    public static final String CURRENT_LOGIN_USER_TYPE="currentLoginedUserType";
	    public static final String CURRENT_SUBSITE_ID="currentSubSiteId";
	    public static final String CURRENT_SUBSITE_INFO="currentSubSiteInfo";
	    public static final String CURRENT_LOGINED_USER_PERMISSION="currentLoginUserPermission";
	    public static String getCurrentSiteName(HttpSession session){
	    	SubSiteEntity site=(SubSiteEntity) session.getAttribute(CURRENT_SUBSITE_INFO);
	    	if(site==null){
	    		return "";
	    	}else{
	    		return site.getSiteName();
	    	}
	    }
	    public static SubSiteEntity getCurrentSiteInfo(HttpSession session){
	    	SubSiteEntity site=(SubSiteEntity) session.getAttribute(CURRENT_SUBSITE_INFO);
	    	return site;
	    }
	    public static Long[] getManagedSiteIds(){
	    	ISubSiteService s=(ISubSiteService) ServiceProxyFactory.getServiceProxy(SubSiteServiceImpl.class);
	    	List<SubSiteEntity> ss=s.getList();
	    	Long[] tmp=new Long[ss.size()];
	    	for(Integer i=0;i<ss.size();i++){
	    		tmp[i]=ss.get(i).getId();
	    	}
	    	return tmp;
	    }
	    public static void setCurrentLoginedUserType(HttpSession session,String type){
	    	session.setAttribute(CURRENT_LOGIN_USER_TYPE, type);
	    }
	    public static String getCurrentLoginedUserType(HttpSession session){
	    	Object obj=session.getAttribute(CURRENT_LOGIN_USER_TYPE);
	    	if(obj==null)
	    		return null;
	    	return (String) obj;
	    }
	    public static void removeCurrentLoginedUserType(HttpSession session){
	    	session.removeAttribute(CURRENT_LOGIN_USER_TYPE);
	    }
	    public static void setCurrentLoginedUserTenant(HttpSession session,TenantEntity tenant){
	    	session.setAttribute(CURRENT_LOGIN_USER_TENANT, tenant);
	    }
	    public static TenantEntity getCurrentLoginedUserTenant(HttpSession session){
	    	TenantEntity te=(TenantEntity) session.getAttribute(CURRENT_LOGIN_USER_TENANT);
	    	return te;
	    }
	    public static void setCurrentLoginedUserInfo(HttpSession session,UserEntity user){
	    	session.setAttribute(CURRENT_LOGIN_USER_ENTTIY, user);
	    	session.setAttribute(CURRENT_SUBSITE_ID, user.getSubSiteId());
	    }
	    public static void setCurrentLoginedSiteInfo(HttpSession session,SubSiteEntity site){
	    	session.setAttribute(CURRENT_SUBSITE_INFO, site);
	    }
	    public static SubSiteEntity getCurrentLoginedSiteInfo(HttpSession session){
	    	return (SubSiteEntity) session.getAttribute(CURRENT_SUBSITE_INFO);
	    }
	    public static UserEntity getCurrentLoginedUserInfo(HttpSession session){
	    	return (UserEntity) session.getAttribute(CURRENT_LOGIN_USER_ENTTIY);
	    }
	    public static void removeCurrentLoginedUserInfo(HttpSession session){
	    	session.removeAttribute(CURRENT_LOGIN_USER_ENTTIY);
	    }
	    public static Long getCurrentSiteId(HttpSession session){
	    	Object l=session.getAttribute(CURRENT_SUBSITE_ID);
	    	if(l==null){
	    		return -1L;
	    	}else{
	    		if(l instanceof Long){
	    			return Long.valueOf(l.toString());
	    		}else{
	    			return -1L;
	    		}
	    	}
	    }
	    
	    public static String getCurrentLoginedUserName(HttpSession session){
	    	Object obj=session.getAttribute(CURRENT_LOGIN_USER_ENTTIY);
	    	if(obj!=null){
	    		UserEntity user=(UserEntity) obj;
	    		return user.getUserName();
	    	}
	    	return null;
	    }
	    public static String getUploadFileBaseDir(){
	    	return "/uploadFiles";
	    }
//		public static String getSiteName() {
//			// TODO Auto-generated method stub
//			return "";
//		}
		public static void removeCurrentTenant(HttpSession session){
			session.removeAttribute(CURRENT_LOGIN_USER_TENANT);
		}
		public static void setCurrentTenant(HttpSession session,TenantEntity currentTenant) {
			
			setCurrentLoginedUserTenant(session,currentTenant);
		}
		public static List<TenantEntity> getCurrentTenant(HttpSession session) {
			Object o=getCurrentLoginedUserTenant(session);
			if(o==null)
				return null;
			return (List<TenantEntity>) o;
		} 
		public static String getTenantFileUploadDir(Long tenantId){

				return "uploadFiles";
		}
		public static String getTenantFileDir(Long tenantId){
			PathUtil p = new PathUtil();
			String root="";
			try {
				root = p.getWebRoot();
				return root+"uploadFiles";
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}

		}

		public static Long getCurrentTenantId(HttpSession session) {
			TenantEntity te=getCurrentLoginedUserTenant(session);
			if(te!=null)
				return te.getId();
			return null;
		}
		protected static List<ExtUserPermissionEntity> getUserAllPermission(Long userId){
//			IUserService userServ=(IUserService) ServiceProxyFactory.getServiceProxy(UserServiceImpl.class);
			BaseController bc=new BaseController();
			IUserRoleService userRoleServ=(IUserRoleService) bc.getBeanFromSpringDefinedBeans("userRoleService");
			IRoleService roleServ=(IRoleService) bc.getBeanFromSpringDefinedBeans("roleService");
			IRolePermissionService rolePerServ=(IRolePermissionService) bc.getBeanFromSpringDefinedBeans("rolePermissionService");
			IFunService funServ=(IFunService) bc.getBeanFromSpringDefinedBeans("funService");
//			IUserRoleService userRoleServ=(IUserRoleService) ServiceProxyFactory.getServiceProxy(UserRoleServiceImpl.class);
//			IRoleService roleServ=(IRoleService) ServiceProxyFactory.getServiceProxy(RoleServiceImpl.class);
//			IRolePermissionService rolePerServ=(IRolePermissionService) ServiceProxyFactory.getServiceProxy(RolePermissionServiceImpl.class);
//			IFunService funServ=(IFunService) ServiceProxyFactory.getServiceProxy(FunServiceImpl.class);
			List<Long> roleIdList=userRoleServ.getRoleIdByUserId(userId);
			String roleHql="";
			for(Long roleId:roleIdList){
				RoleEntity role=roleServ.getEntityById(roleId);
				if(role!=null){
					roleHql+=role.getId()+",";
				}
			}
			if(roleHql.trim().length()>0){
				roleHql=roleHql.substring(0,roleHql.length()-1);
			}
			List<RolePermissionEntity> rolePerList=rolePerServ.getListByRoleIds(roleHql);
			List<ExtUserPermissionEntity> userPermissionList=new ArrayList<ExtUserPermissionEntity>();
			for(RolePermissionEntity rp:rolePerList){
				FunEntity fun=funServ.getEntityById(rp.getFunId());
				if(fun!=null && fun.getIsLocked()==false){
					ExtUserPermissionEntity ext=new ExtUserPermissionEntity(rp);
					ext.setFunCode(fun.getWebName());
					ext.setFunName(fun.getFunName());
					userPermissionList.add(ext);
				}
			}
			return userPermissionList;
		}
		public static void initUserAllPermission(HttpSession session){
			UserEntity user=SysUtil.getCurrentLoginedUserInfo(session);
			if(user==null)
				return;
			List<ExtUserPermissionEntity> lst=getUserAllPermission(user.getId());
			String debug=IbpdCommon.getInterface().getPropertiesValue("system.debug.enable");
			if(debug!=null && debug.trim().toLowerCase().equals("true")){
				for(ExtUserPermissionEntity ext:lst){
					IbpdLogger.getLogger(SysUtil.class).info("==modelId:"+ext.getModelId()+"======modelType:"+ext.getTypeId()+"=====funId:"+ext.getFunId()+"=====funName:"+ext.getFunName()+"=====funCode:"+ext.getFunCode());
				}	
			}
			session.setAttribute(CURRENT_LOGINED_USER_PERMISSION, lst);
		}
		public static void clearUserPermission(HttpSession session){
			session.removeAttribute(CURRENT_LOGINED_USER_PERMISSION);
		}
		public static Boolean checkPermissionIsEnable(HttpSession session,String funCode,Long modelId,Integer modelType){
			Object o=session.getAttribute(CURRENT_LOGINED_USER_PERMISSION);
			Boolean rtn=false;
			if(o==null)
				return rtn;
			List<ExtUserPermissionEntity> lst=(List<ExtUserPermissionEntity>) o;
			for(ExtUserPermissionEntity e:lst){
				if(modelType.equals(PermissionModelEntity.MODEL_TYPE_FUNMODEL)){
					if(e.getFunCode().toLowerCase().trim().equals(funCode.trim().toLowerCase())){
						rtn=true;
						break;
					}
				}else if(modelType.equals(PermissionModelEntity.MODEL_TYPE_SITE)){
					if(e.getFunCode().toLowerCase().trim().equals(funCode.trim().toLowerCase()) && e.getModelId().equals(modelId) && e.getTypeId().equals(modelType)){
						rtn=true;
						break;
					}
				}else if(modelType.equals(PermissionModelEntity.MODEL_TYPE_NODE)){
					if(e.getFunCode().toLowerCase().trim().equals(funCode.trim().toLowerCase()) && e.getModelId().equals(modelId) && e.getTypeId().equals(modelType)){
						rtn=true;
						break;
					}					
				}
			}
			if(modelType.equals(PermissionModelEntity.MODEL_TYPE_NODE) && rtn==false){
				INodeService nodeServ=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
				NodeEntity ne=nodeServ.getEntityById(modelId);
				if(ne==null){
					return false;
				}else{
					if(ne.getParentId()!=-1L)
						return checkPermissionIsEnable(session,funCode,ne.getParentId(),modelType);
					else
						return false;
				}
			}
			return rtn;
		}

		private static final String LOGIN_DES_KEY="login_des_key";
		public static void setLoginDesKey(String uuid, HttpServletRequest req) {
			req.getSession().setAttribute(LOGIN_DES_KEY, uuid);
		}
		public static String getLoginDesKey(HttpServletRequest req){
			return req.getSession().getAttribute(LOGIN_DES_KEY).toString();
		}
		
}
